<?php
namespace app\admin\controller;
use think\Controller;
class GoodsOrders extends Controller
{
    function ordersList()
    {
        $adminId = session('uid','','admin');
        $list = db('goods_orders')//->where('is_del',0);
                ->alias('og')
                ->field('og.*,g.goods_name,g.brand')
                ->join('goods g','g.id=og.goods_id')
                ->where('g.is_del',0);
        if(input('status') || input('status')=='0')
        {
            $list = $list->where('og.status',input('status'));
        }
        // else
        // {
        //     $list = $list->where('og.status',1);
        // }
        if(input('goods_id'))
        {
            $list = $list->where('og.goods_id',input('goods_id'));
        }
        if(input('admin_id'))
        {
            $list = $list->where('og.admin_id',input('admin_id'));
        }
        if(input('type'))
        {
            $list = $list->where('og.type',input('type'));
        }
        else
        {
            $list = $list->where('og.type',2);
        }
        
        if(session('group_id','','admin') == 5 || session('group_id','','admin') == 2)
        {
            $list = $list->where('og.admin_id',$adminId);
        }
        $list = $list->order('og.id desc')->paginate(10,false,['query' => request()->param()]);
        foreach ($list as $k=>$v)
        {
            /*if($v['express_num'] && $v['express_status'] < 4 && $v['express_update_time']-43200 < time() )
            {
                $data = $this->getOrderTracesByJson($v['express_num']);
                print_r($data);
                $exData = $exName = '';
                $v['express_name'] = strtolower(substr($v['express_num'],0,3)) == 'dpk'?'debangwuliu':$v['express_name'];
                $exName = $v['express_name']?:json_decode(file_get_contents("http://www.kuaidi.com/index-ajaxselectinfo-{$v['express_num']}.html"),true)[0]['exname'];
                
                if($exName)
                {
                    $exData = json_decode(file_get_contents("http://www.kuaidi.com/index-ajaxselectcourierinfo-{$v['express_num']}-{$exName}-KUAIDIC0M".time().rand(100,999).".html"),true);
                    if($exData['status'] && $exData['data'])
                    {
                        //db('goods_orders')->where('id',$v['id'])->update(['express_name'=>$exName,'express_update_time'=>time(),'express_last_data'=>$exData['data'][0]['time'].$exData['data'][0]['context'] ,'express_status'=>$exData['status'] ]);
                    }
                }
            }*/
        }
        $goodsList = db('goods')->where('status',1)->where('is_del',0)->order('id DESC')->select();
        $adminList = db('admin')->where('status',1)->where('group_id','IN','5,2')->order('id DESC')->select();
        $this->assign([
            'list'=>$list,
            'goodsList'=>$goodsList,
            'adminList'=>$adminList,
        ]);
        return view();
    }

    /**
     * 礼品管理
     * 发货汇总
     */
    function ordersListSummary()
    {
        $adminId = session('uid','','admin');
        $list = db('goods_orders')//->where('is_del',0);
                ->alias('og')
//                ->field('og.*,g.goods_name,g.brand')
                ->field('og.admin_id,og.count,og.add_time,g.goods_name,g.brand')
                ->join('goods g','g.id=og.goods_id')
                ->where('g.is_del',0);
//        if(input('status') || input('status')=='0')
//        {
//            $list = $list->where('og.status',input('status'));
//        }
        $list = $list->where('og.status',1);
        // else
        // {
        //     $list = $list->where('og.status',1);
        // }
        if(input('goods_id'))
        {
            $list = $list->where('og.goods_id',input('goods_id'));
        }
        if(input('admin_id'))
        {
            $list = $list->where('og.admin_id',input('admin_id'));
        }
//        if(input('type'))
//        {
//            $list = $list->where('og.type',input('type'));
//        }
//        else
//        {
//            $list = $list->where('og.type',2);
//        }
        $list = $list->where('og.type',2);

        if(session('group_id','','admin') == 5 || session('group_id','','admin') == 2)
        {
            $list = $list->where('og.admin_id',$adminId);
        }
        $list = $list->order('og.id desc')->select();

        $list_arr = [];
        foreach ($list as $key => $val){
            $list_arr[$val['brand'] . '|' . $val['goods_name']][] = $val;
        }

//        echo "<pre>";
////        print_r(count($list_arr));
//        print_r($list_arr);
//        die;

        //计算 每个礼品=》各个业务员 发货数量
        $list_arr_count = [];
        foreach($list_arr as $key => $val){
            $temp = $val;
            foreach($temp as $k => $v){
                $count = 0;
                foreach($val as $kk => $vv){
                    if($v['admin_id'] == $vv['admin_id']){
                        $count += $vv['count'];
                    }
                }
                $list_arr_count[$key][$v['admin_id']] = $count;
            }
        }

//        echo "<pre>";
//        print_r($list_arr_count);
//        die;

        $dataList = [];
        foreach($list_arr_count as $key => $val){
            $dataList[] = $key;
        }

//        echo "<pre>";
//        print_r($dataList);
//        print_r($list_arr_count);
//        die;

        /*foreach($dataList as $key => $val){
            foreach($list_arr_count as $k => $v){
//                print_r($v);die;
                foreach($v as $kk =>$vv){
//                    print_r($kk);die;
                    $dataList[$key][$kk] = $kk;
                    $dataList[$key][$kk] = $vv;
//                $dataList[][] = $k;
//                $dataList[][] = $v;
                }
            }
        }*/
//
//        echo "<pre>";
//        print_r($dataList);
//        die;

        $goodsList = db('goods')->where('status',1)->where('is_del',0)->order('id DESC')->select();
        $adminList = db('admin')->where('status',1)->where('group_id','IN','5,2')->order('id DESC')->select();
        $this->assign([
            'list'=>$list_arr_count,
            'goodsList'=>$goodsList,
            'adminList'=>$adminList,
        ]);
        return view();
    }
    
    function stockList()
    {
        $adminId = session('uid','','admin');
        $list = db('goods_orders')//->where('is_del',0);
                ->alias('og')
                ->field('og.*,g.goods_name,g.brand')
                ->join('goods g','g.id=og.goods_id')
                ->where('g.is_del',0)
                ->where('og.status','>=',0);
        if(input('goods_id'))
        {
            $list = $list->where('og.goods_id',input('goods_id'));
        }
        if(session('group_id','','admin') == 5 || session('group_id','','admin') == 2)
        {
            $list = $list->where('og.admin_id',$adminId);
        }
        if(input('type'))
            $list = $list->where('og.type',input('type'));
            
        $list = $list->order('og.id desc')->paginate(20,false,['query' => request()->param()]);
        
        $goodsList = db('goods')->where('is_del',0)->order('id DESC')->select();
        $adminList = db('admin')->where('status',1)->where('group_id','IN','5,2')->order('id DESC')->select();
        $this->assign([
            'list'=>$list,
            'goodsList'=>$goodsList,
            'adminList'=>$adminList,
        ]);
        return view();
    }
    
    function ordersAdd()
    {
        if(request()->isAjax())
        {
            $data = input('post.')['data'];
            $data['admin_id'] = session('uid','','admin');
            $data['add_time'] = time();
            $data['type'] = 2;
            $data['status'] = 0;
            $sqlStatus = db('goods_orders')->insert($data);
            if($sqlStatus  )
            {
                db('goods')->where('id', $data['goods_id'])->update(['stock' => ['dec', $data['count']]]);
                return ['msg'=>'操作成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        }
        $goodsList = db('goods')->where('is_del',0)->where('status',1)->select();
        $clientList = db('client')->where('status',4);
        if(session('group_id','','admin') != 1 && session('group_id','','admin') != 8)
            $clientList = $clientList->where('xaid',session('uid','','admin'));
        $clientList = $clientList->order('qiandan_time DESC')->select();
        $this->assign([
            'goodsList'=>$goodsList,
            'clientList'=>$clientList,
        ]);
        return view();
    }
    
    function ordersSend()
    {
        if(input('id'))
        {
            if(request()->isAjax())
            {
                $info = db('goods_orders')->find(input('id'));
                $data = input('post.')['data'];
                $data['id'] = input('id');
                $data['send_admin_id'] = session('uid','','admin');
                $data['send_time'] = time();
                $sqlStatus = db('goods_orders')->update($data);
                if($sqlStatus  )
                {
                    if($data['status'] == -1){
                        db('goods')->where('id', $info['goods_id'])->update(['stock' => ['inc', $info['count']]]);
                    }
                    return ['msg'=>'操作成功','icon'=>1];
                }
                else
                {
                    return ['msg'=>'操作失败','icon'=>2];
                }
            }
            

        }
    }
    
    function ordersEdit()
    {
        if(input('id'))
        {
            if(request()->isAjax())
            {
                $info = db('goods_orders')->find(input('id'));
                $data = input('post.')['data'];
                $data['id'] = input('id');
                $sqlStatus = db('goods_orders')->update($data);
                if($sqlStatus  )
                {
                    return ['msg'=>'操作成功','icon'=>1];
                }
                else
                {
                    return ['msg'=>'操作失败','icon'=>2];
                }
            }
        }
    }
    
    function ordersView()
    {
        if(input('id'))
        {
            $info = db('goods_orders')->alias('o')->field('o.*,g.goods_name')->join('goods g','g.id=o.goods_id')->where('o.id',input('id'))->find();
            $this->assign([
                'info'=>$info,
            ]);
            return view();
        }
    }
    
    function ordersDel()
    {
        if(input('id'))
        {
            $sqlStatus = db('goods_orders')->where('id',input('id'))->update(['is_del'=>1]);
            if($sqlStatus)
            {
                return ['msg'=>'操作成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        }
    }
    
    function orderCheck()
    {
        if(input('id'))
        {
            $sqlStatus = db('goods_orders')->where('id',input('id'))->update(['check_status'=>1]);
            if($sqlStatus)
            {
                return ['msg'=>'操作成功','icon'=>1];
            }
            else
            {
                return ['msg'=>'操作失败','icon'=>2];
            }
        }
    }
    
    
    function getOrderTracesByJson($expressNum){
      // 组装应用级参数
    	$requestData= "{".
        "'OrderCode': '',".
        "'CustomerName': '',".
        "'LogisticCode': '{$expressNum}',".
        "}";
      // 组装系统级参数
    	$datas = array(
            'EBusinessID' => '1771160',
            'RequestType' => '8002', //快递查询接口指令8002/地图版快递查询接口指令8004
            'RequestData' => urlencode($requestData),
            'DataType' => '2',
        );
        $datas['DataSign'] = urlencode(base64_encode(md5($requestData.'18f1ccc9-e97d-49e6-a6e5-22cc7a409eb1')));
      //以form表单形式提交post请求，post请求体中包含了应用级参数和系统级参数
      $postdata = http_build_query($datas);
      $options = array(
        'http' => array(
          'method' => 'POST',
          'header' => 'Content-type:application/x-www-form-urlencoded',
          'content' => $postdata,
          'timeout' => 15 * 60 // 超时时间（单位:s）
        )
      );
      $context = stream_context_create($options);
      $result = file_get_contents('https://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx', false, $context);
    	
    	//根据公司业务处理返回的信息......
    	
    	return $result;
    }
    
    
}